Draw arrow on canvas tag

后端 未结 12 914
小鲜肉
小鲜肉 2020-11-27 13:50

I want to draw an arrow using the canvas tag, javascript. I\'ve made it using the quadratic function, but I\'m having problems to calculate the angle of rotation of the arro

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 13:59

    Here is another method to draw arrows. It uses the triangle method from here: https://stackoverflow.com/a/8937325/1828637

    A little helper function.

    function canvas_arrow(context, fromx, fromy, tox, toy, r){
        var x_center = tox;
        var y_center = toy;
    
        var angle;
        var x;
        var y;
    
        context.beginPath();
    
        angle = Math.atan2(toy-fromy,tox-fromx)
        x = r*Math.cos(angle) + x_center;
        y = r*Math.sin(angle) + y_center;
    
        context.moveTo(x, y);
    
        angle += (1/3)*(2*Math.PI)
        x = r*Math.cos(angle) + x_center;
        y = r*Math.sin(angle) + y_center;
    
        context.lineTo(x, y);
    
        angle += (1/3)*(2*Math.PI)
        x = r*Math.cos(angle) + x_center;
        y = r*Math.sin(angle) + y_center;
    
        context.lineTo(x, y);
    
        context.closePath();
    
        context.fill();
    }
    

    And here is a demonstration of it to draw arrows at the start and at the end of a line.

    var can = document.getElementById('c');
    var ctx = can.getContext('2d');
    
    ctx.lineWidth = 10;
    ctx.strokeStyle = 'steelblue';
    ctx.fillStyle = 'steelbllue'; // for the triangle fill
    ctx.lineJoin = 'butt';
    
    ctx.beginPath();
    ctx.moveTo(50, 50);
    ctx.lineTo(150, 150);
    ctx.stroke();
    
    canvas_arrow(ctx, 50, 50, 150, 150, 10);
    canvas_arrow(ctx, 150, 150, 50, 50, 10);
    
    function canvas_arrow(context, fromx, fromy, tox, toy, r){
    	var x_center = tox;
    	var y_center = toy;
    	
    	var angle;
    	var x;
    	var y;
    	
    	context.beginPath();
    	
    	angle = Math.atan2(toy-fromy,tox-fromx)
    	x = r*Math.cos(angle) + x_center;
    	y = r*Math.sin(angle) + y_center;
    
    	context.moveTo(x, y);
    	
    	angle += (1/3)*(2*Math.PI)
    	x = r*Math.cos(angle) + x_center;
    	y = r*Math.sin(angle) + y_center;
    	
    	context.lineTo(x, y);
    	
    	angle += (1/3)*(2*Math.PI)
    	x = r*Math.cos(angle) + x_center;
    	y = r*Math.sin(angle) + y_center;
    	
    	context.lineTo(x, y);
    	
    	context.closePath();
    	
    	context.fill();
    }

提交回复
热议问题