gpt4 book ai didi

javascript - 创建 Canvas 光标,无法存储颜色

转载 作者:行者123 更新时间:2023-11-28 01:48:40 24 4
gpt4 key购买 nike

在尝试了许多不同的事情之后,我终于得到了一个光标,可以在进入 Canvas 时调整大小,但不知道如何保存颜色。

我的鼠标基于这个演示:http://jsfiddle.net/AbdiasSoftware/XcjX9/

function loop() {
var color = 'rgb(' + ((255 * Math.random())|0) + ','
+ ((255 * Math.random())|0) + ','
+ ((255 * Math.random())|0) + ')';
makeCursor(color);
setTimeout(loop, 1000);
}

function makeCursor(color) {

var cursor = document.createElement('canvas'),
ctx = cursor.getContext('2d');

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

ctx.strokeStyle = color;

ctx.lineWidth = 4;
ctx.lineCap = 'round';

ctx.moveTo(2, 12);
ctx.lineTo(2, 2);
ctx.lineTo(12, 2);
ctx.moveTo(2, 2);
ctx.lineTo(30, 30)
ctx.stroke();

document.body.style.cursor = 'url(' + cursor.toDataURL() + '), auto';
}

这是我当前的代码:http://jsfiddle.net/Vw4yD/

function init(){
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];

//Spawn mouse on canvas enter.
elem.addEventListener('mouseover', function() {
makeCursor();
});

//Destroy mouse on canvas exit.
elem.addEventListener('mouseout', function() {
document.body.style.cursor = 'auto';
});

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;

var brushHeight = document.getElementById('brushHeight').value;
var brushWidth = document.getElementById('brushWidth').value;
var brushColor = document.getElementById('brushColor').value;

// Render elements.
elements.forEach(function(element) {
//Listen for controls.
context.fillStyle = brushColor;
context.fillRect(x, y, brushWidth, brushHeight);
});
// Add element.
elements.push({
colour: brushColor,
width: brushWidth,
height: brushHeight,
});
}, false);

//Draw Mouse.
function makeCursor() {
var cursor = document.createElement('canvas'),
cursorctx = cursor.getContext('2d');

var x = event.pageX - elemLeft,
y = event.pageY - elemTop;

var cursorLeft = cursor.offsetLeft;
cursorRight = cursor.offsetTop;

var brushHeight = document.getElementById('brushHeight').value;
var brushWidth = document.getElementById('brushWidth').value;
var brushColor = document.getElementById('brushColor').value;

cursor.width = brushWidth;
cursor.height = brushHeight;

cursorctx.fillStyle = brushColor;
cursorctx.fillRect(x, y, brushWidth, brushHeight);
cursorctx.fill();

document.body.style.cursor = 'url(' + cursor.toDataURL() + '), auto';
}
};

鼠标应该在进入 Canvas 时调整大小(确实如此)并改变颜色,无论如何你们知道如何让它工作吗?这让我感到难过,我已经为此工作了大约一整天,但无论如何都找不到使用矩形来完成它,抚摸工作但对于我需要完成的基本工作来说太复杂了。对不起,如果这篇文章写得不好,我在过去的一天里睡得很少。

最佳答案

给你http://jsfiddle.net/Vw4yD/1/

我已经删除了光标的 xy。它们应该等于 0,因为它是相对于光标 Canvas ,而不是主 Canvas 。

关于javascript - 创建 Canvas 光标,无法存储颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21256217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com