图像缩放和旋转javascript

Image scale and rotate javascript

本文关键字:javascript 旋转 缩放 图像      更新时间:2023-09-26

我正在尝试旋转我的图像并缩放它。图片实际大小- 300x434转换为8x8.

    var c = dc.create('canvas', {
        id:'canvas_'+_id, 
        width:8, // HERE!!! 8x8
        height:8, // HERE!!! 8x8
    }, dom.byId('canses'));
    var ctx = dom.byId('canvas_'+_id).getContext('2d');
    var img = new Image();
    img.src = res;
    ctx.translate(img.width/2, img.height/2);
    ctx.rotate(rot*(Math.PI/180));
    ctx.translate(-img.width/2, -img.height/2);
    ctx.drawImage(img, 0, 0, 8, 8); // HERE!!! 8x8

但是canvas是空的;如果使用初始大小,则一切正常。

    var c = dc.create('canvas', {
        id:'canvas_'+_id, 
        width:300,
        height:434,
    }, dom.byId('canses'));
    var ctx = dom.byId('canvas_'+_id).getContext('2d');
    var img = new Image();
    img.src = res;
    ctx.translate(img.width/2, img.height/2);
    ctx.rotate(rot*(Math.PI/180));
    ctx.translate(-img.width/2, -img.height/2);
    ctx.drawImage(img, 0, 0);

你能帮我吗?谢谢!

以固定大小呈现围绕中心旋转的图像

// image is the image
// ctx is the context
var x = 100;  // where the center of the image will be
var y = 100;
var width = 8; // size to draw
var height = 8;
// scale and translate
ctx.setTransform(width / image.width, 0, 0, height / image.height, x, y);
// rotate image
ctx.rotate(rot);
// draw image
ctx.drawImage(image, -image.width / 2,-image.height / 2);
// resets the default transform;
ctx.setTransform(1,0,0,1,0,0)