简体   繁体   中英

Using transform and scaling from center point

I have a canvas where by I draw my circle at an angle using the transform function.

But i also use scale and translate for camera zoom and position. The problem is the transform function is causing the scaling to be based on it's top left corner, and I cannot figure out how to fix this problem.

This is my code:

function draw(){
    ctx.clearRect(0,0,element.width,element.height);        
    ctx.save();      

    ctx.setTransform(scale, 0.01, 0.01, 0.3*scale, scale, element.height/2*0.7);      
    ctx.translate(0-(camera.x - element.width/2),0-(camera.y-element.height/2));      

    for(var i = 0; i < obj.length; i++){
        ctx.beginPath();
        ctx.arc(0,0,obj[i].radius,0,Math.PI*2);  
        ctx.lineWidth = 4.5;
        ctx.strokeStyle = "white";
        ctx.stroke();
    }
    ctx.restore();
    requestAnimationFrame(draw);
}

If you zoom in and out you can see the problem where by it is not staying in the correct place, the camera is drifting and I need to correct for that: http://jsfiddle.net/ub97gdgj/

How do i fix this anchor point problem?

Before using the transform function, the whole image could be moved to make the rotation point at the center of the image.

ctx.setTransform(scale, 0.01, 0.01, 0.3*scale, element.width/2, element.height/2);

The 5th and 6th params of the ctx.setTransform are used for translate function.

http://jsfiddle.net/ub97gdgj/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM