gpt4 book ai didi

javascript - 在 JavaScript 中使用鼠标事件在 Canvas 上绘制直线

转载 作者:行者123 更新时间:2023-12-01 02:08:56 25 4
gpt4 key购买 nike

我正在尝试使用鼠标事件在 Canvas 上画一条直线。我是java脚本的新手。任何人都可以提供帮助或向我提供帮助吗?

最佳答案

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}

canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">

var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;

var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];

function draw() {
ctx.fillStyle = "#333333";
ctx.fillRect(0,0,canvasWidth,canvasHeight);

ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();

for (var i = 0; i < existingLines.length; ++i) {
var line = existingLines[i];
ctx.moveTo(line.startX,line.startY);
ctx.lineTo(line.endX,line.endY);
}

ctx.stroke();

if (isDrawing) {
ctx.strokeStyle = "darkred";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
}
}

function onmousedown(e) {
if (hasLoaded && e.button === 0) {
if (!isDrawing) {
startX = e.clientX - bounds.left;
startY = e.clientY - bounds.top;

isDrawing = true;
}

draw();
}
}

function onmouseup(e) {
if (hasLoaded && e.button === 0) {
if (isDrawing) {
existingLines.push({
startX: startX,
startY: startY,
endX: mouseX,
endY: mouseY
});

isDrawing = false;
}

draw();
}
}

function onmousemove(e) {
if (hasLoaded) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;

if (isDrawing) {
draw();
}
}
}

window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.onmousedown = onmousedown;
canvas.onmouseup = onmouseup;
canvas.onmousemove = onmousemove;

bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
hasLoaded = true;

draw();
}

</script>
</body>
</html>

关于javascript - 在 JavaScript 中使用鼠标事件在 Canvas 上绘制直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885020/

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