图像缩放和旋转javascript

时间:2016-08-25 12:01:42

标签: javascript image canvas

我正在尝试旋转我的图像并在缩放之后。图像的实际尺寸 - 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

但画布是空的;(。如果使用初始大小,一切正常。

    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);
你帮我吗?谢谢! (对不起我的英文)

1 个答案:

答案 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)