canvas 画箭头
2022-07-08 本文已影响0人
skoll
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="1000px" height="1000px"></canvas>
<script>
const canvas=document.getElementById('canvas')
const ctx=canvas.getContext('2d')
// ctx.fillRect(10,10,55,50)
// ctx.fillStyle='rgba(0,0,200,0.5)'
// ctx.strokeRect(0,0,50,50)
// draw(ctx)
// drawSin()
// drawWork()
function draw(ctx){
ctx.beginPath()
ctx.moveTo(0,0)
ctx.lineTo(200,50)
ctx.closePath()
ctx.stroke()
}
function drawSin(){
ctx.beginPath()
ctx.moveTo(0,0)
ctx.lineTo(100,0)
ctx.lineTo(0,100)
ctx.closePath()
ctx.fill()
ctx.stroke()
ctx.scale(0.5,0.5)
}
function drawWork(){
ctx.beginPath()
ctx.moveTo(19.568918244460175,7.465526336640618)
ctx.lineTo(1,1)
ctx.lineTo(19.82291145591323,-4.683815611197273)
ctx.closePath()
ctx.fill()
ctx.stroke()
}
var isMove = false;
//鼠标事件
var x
var y
let img=new Image()
img.src="./arrow.png"
canvas.onmousedown = function (e) {
x = e.clientX;
y = e.clientY;
isMove = true;
}
canvas.onmousemove = function (e) {
let cx = e.clientX;
let cy = e.clientY;
const disX=cx-x
const disY=-(cy-y)
if (isMove) {
ctx.clearRect(0, 0, 1000, 1000)
ctx.beginPath()
ctx.moveTo(x, y);
ctx.lineTo(cx, cy);
ctx.save()
ctx.translate(cx, cy);
const angle=calcAngle(disX,disY)
console.log(angle)
ctx.rotate(angle*Math.PI/180)
ctx.drawImage(img,0,0,30,30)
ctx.restore()
ctx.stroke();
}
}
function calcAngle(x,y){
return 90-(Math.atan2(y, x) * 180 / Math.PI);
}
canvas.onmouseup = function (e) {
isMove = false;
}
</script>
</body>
</html>