如何解决js画布弧中的粗笔画
我试图在画布上画一条弧线。但由于某种原因,它并不顺利。请注意,我也在代码中添加了一些 css 以及响应式元标记。请检查代码段。
有什么办法可以让它顺利吗?
现在添加了一个片段。请注意,弧线是在 draw 函数中绘制的,我使用屏幕外画布将结果返回以减少绘制调用。
window.onload = main;
let canvas;
let frame;
class Widget {
canvas;
parent;
constructor() {
this.canvas = document.createElement("canvas");
}
}
class Frame extends Widget{
constructor(parent) {
super();
this.canvas.style.display = "block";
this.canvas.height = window.innerHeight;
this.canvas.width = window.innerWidth;
this.parent = parent;
this.parent.appendChild(this.canvas);
this.buffer = document.createElement("canvas");
this.buffer.height = this.canvas.height;
this.buffer.width = this.canvas.width;
}
blit() {
let context = this.canvas.getContext("2d");
context.drawImage(this.buffer,0);
}
}
function main() {
frame = new Frame(document.body);
animation();
}
function animation() {
draw(frame.buffer);
frame.blit();
window.requestAnimationFrame(animation);
}
function draw(canvas) {
let ctx = canvas.getContext("2d");
ctx.clearRect(0,canvas.width,canvas.height);
ctx.fillRect(0,canvas.height);
ctx.arc(100,100,2*Math.PI);
ctx.linewidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
}
<!DOCTYPE html>
<html>
<head>
<Meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<style>
html,body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
</style><body></body></html>
解决方法
好吧,我找到了问题和解决方案。 我需要在我的 arc() 函数调用之前添加 beginPath()。
function draw(canvas) {
let ctx = canvas.getContext("2d");
ctx.clearRect(0,canvas.width,canvas.height);
ctx.fillRect(0,canvas.height);
// beginPath() is important!!!
ctx.beginPath()
//
ctx.arc(100,100,2*Math.PI);
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
}
在添加 beginPath() 之前:
添加 beginPath() 后:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。