javascript - 如何使用 JavaScript 中的单击事件更改 HTML 画布中的线宽
问题描述
我想通过单击事件将画布中的线宽从 5 更改为 10,但它在 JavaScript 中不起作用
function draw(e) {
if (!painting) {
return;
}
exitdraw(e);
c.lineWidth = 5;
c.lineTo(e.clientX, e.clientY);
c.lineCap = 'round';
c.strokeStyle = 'aqua';
c.stroke();
c.beginPath();
c.moveTo(e.clientX, e.clientY);
}
//this is the listener i want to change the linewidth
var canvas = document.querySelector('#canvas');
var btn = document.getElementById('button');
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
})
解决方案
<button onclick="changeWidth()">Change Width</button>
<br />
<canvas height="150" id="canvas" width="200"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var lineWidth = 5;
function draw() {
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.arc(100, 75, 32, 0, 2 * Math.PI);
ctx.stroke();
}
draw();
function changeWidth() {
lineWidth = 10;
draw();
}
</script>
推荐阅读
- python - networkx 中的最短路径,在源和目标之间访问多个“关键”节点
- javascript - 反应式表单:如何禁用输入元素所需属性的默认验证?
- php - 无法在 php 中使用 sqlsrv 执行存储过程
- jquery - 为什么我在不使用任何 gem 或 js 库的情况下在 Rails 中接收 jquery 访问?
- mongodb - 如何在 Kubernetes 上部署的 mongodb 中持久化数据
- java - 在 Java Map 中为每个键分配多个值
- dynamodb-queries - 在不使用 SCAN 的情况下获取与非关键属性 dynamoDB 匹配的所有记录
- javascript - 如果 URL 仅包含 .co,如何显示验证消息
- javascript - 收到错误 this.setState 不是类组件中的函数
- java - 我无法映射模型和 DTO 无法执行语句;SQL [n/a] 约束 [null]