gpt4 book ai didi

html - 在 HTML5 canvas 上点两下鼠标画一条线?

转载 作者:太空狗 更新时间:2023-10-29 13:24:46 24 4
gpt4 key购买 nike

如何在 Canvas 上点击两次鼠标画一条线?

最佳答案

代码很简单,但是基础一定要好:

演示:http://jsfiddle.net/NpDdt/10/

JavaScript:

var clicks = 0;
var lastClick = [0, 0];

document.getElementById('canvas').addEventListener('click', drawLine, false);

function getCursorPosition(e) {
var x;
var y;

if (e.pageX != undefined && e.pageY != undefined) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}

return [x, y];
}

function drawLine(e) {
context = this.getContext('2d');

x = getCursorPosition(e)[0] - this.offsetLeft;
y = getCursorPosition(e)[1] - this.offsetTop;

if (clicks != 1) {
clicks++;
} else {
context.beginPath();
context.moveTo(lastClick[0], lastClick[1]);
context.lineTo(x, y, 6);

context.strokeStyle = '#000000';
context.stroke();

clicks = 0;
}

lastClick = [x, y];
};

关于html - 在 HTML5 canvas 上点两下鼠标画一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6035764/

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