简体   繁体   中英

zoom jpeg image on canvas with mousewheel event in javascript

I have written simple code in java script which adds JPEG image on canvas & add line on that image with simple mousedown & mouseup event. Now i wanted to add zoom-in & zoom-out effect on that image.can anybody help me out?

my js file looks as below.

var canvas;
var context;
var width;
var height;
var finalPos = {x: 0, y: 0};
var startPos = {x: 0, y: 0};


function main() {

    canvas = document.getElementById('imageCanvas');
    context = canvas.getContext('2d');
    loadImage();

    width = canvas.width;
    height = canvas.height;

    var canvasOffset = $('#imageCanvas').offset();
    function line(cnvs) {
        cnvs.beginPath();
        cnvs.moveTo(startPos.x, startPos.y);
        cnvs.lineTo(finalPos.x, finalPos.y);
        cnvs.stroke();
    }

    $('#imageCanvas').mousedown(function (e) {
        context.strokeStyle = 'blue';
        context.lineWidth = 5;
        context.lineCap = 'round';
        context.beginPath();
        startPos = {x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top};
    });

    $('#imageCanvas').mouseup(function (e) {
        // Replace with var that is second canvas
        finalPos = {x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top};
        line(context);
    });
}
;

function loadImage() {
    system_image = new Image();
    system_image.src = 'img/Google_OH_406TwentySecondStreet.jpg';

    system_image.onload = function () {
        context.drawImage(system_image, 0, 0, width, height);
    };
}

You can use scale function on mousewheel

context.scale(scaleValue, scaleValue);

You must do that before drawimage on context.

I have created the example here: [link]: http://jsfiddle.net/itsjawad/5wohz3r1/

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