gpt4 book ai didi

javascript - 更改 Canvas 以绘制线条

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

我在关于如何在 Canvas 中绘制的 stackoverflow 问题中找到了这个 http://jsfiddle.net/ArtBIT/kneDX/但我希望它在没有圆圈的情况下连续画线,但线条流畅。需要修改的代码如下:

ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};

最佳答案

您可以使用 Bresenham's line algorithm找到鼠标开始和结束之间的所有点,然后使用 fillRect 填充之间的点。您需要使用线算法的原因是因为如果用户移动鼠标太快,您将不会得到实线,而是有间隙的线。为此,我对您的功能进行了相当多的修改。您还可以传递线条粗细值来更改您希望描边的大小。请注意,使用 arcs 也可以应用同样的方法,我更喜欢 rect

Live Demo

   (function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element

function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
canvas.lastX = 0;
canvas.lastY = 0;
return canvas;
}

function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;

// define a custom fillCircle method
ctx.fillCircle = function(x1, y1, x2, y2, fillColor, lineThickness) {
this.fillStyle = fillColor;

var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep) {
var x = x1;
x1 = y1;
y1 = x;

var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;

var y = y1;
y1 = y2;
y2 = y;
}

var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;

if (y1 < y2) {
yStep = 1;
}

for (var x = x1; x < x2; x++) {
if (steep) {
this.fillRect(y, x, lineThickness, lineThickness);
} else {
this.fillRect(x, y, lineThickness, lineThickness);
}

error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}

};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");

// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;

ctx.fillCircle(mouseX,mouseY,canvas.lastX,canvas.lastY,"#000",1);

canvas.lastX = mouseX;
canvas.lastY = mouseY;

};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
canvas.lastX = e.pageX - this.offsetLeft;
canvas.lastY = e.pageY - this.offsetTop;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}

var container = document.getElementById('canvas');
init(container, 200, 200, '#ddd');

})();​

关于javascript - 更改 Canvas 以绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13892579/

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