Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - assign color to mouse cursor using CSS

How can I assign color to the mouse cursor in a web-page?

Can anyone suggest me a way to do it using any of the technologies e.g. HTML, CSS, JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to add the possibility to dynamically adding a cursor without providing an image but generating it on client with JavaScript and Canvas.

Demo contains a simple cursor drawn with shapes, but this could just as easily have been images, video and so forth (everything a canvas support).

Fiddle (updated 5/2016 for Firefox - moved from document to element).

Note: FireFox has problem when the cursor is changed so frequent as in this demo - updated to change only once per second. FF clears the cursor when setting a new image but since the new image needs to be decoded it shows the default in the mean time. Chrome waits until the image is decoded before switching over.

In any case it is merely to show it can be done using canvas - test demo using Chrome and don't change mouse so often :-).

The animation loop which here changes color randomly to demonstrate:

function loop() {

    var color = 'rgb(' + ((255 * Math.random())|0) + ','
                       + ((255 * Math.random())|0) + ','
                       + ((255 * Math.random())|0) + ')';
    makeCursor(color);

    setTimeout(loop, 1000);
}

The cursor maker:

function makeCursor(color) {

    // create off-screen canvas
    var cursor = document.createElement('canvas'),
        ctx = cursor.getContext('2d');

    cursor.width = 16;
    cursor.height = 16;

    // draw some shape for sake of demo
    ctx.strokeStyle = color;

    ctx.lineWidth = 2;
    ctx.moveTo(2, 10);
    ctx.lineTo(2, 2);
    ctx.lineTo(10, 2);
    ctx.moveTo(2, 2);
    ctx.lineTo(30, 30)    
    ctx.stroke();

    // set image as cursor (modern browsers can take PNGs as cursor).
    element.style.cursor = 'url(' + cursor.toDataURL() + '), auto';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...