background-image resized to draw on canvas
I am trying to download a canvas image based on sketch.js and the solution I find is as below. I previously set up and resized a background image on the canvas like this on the SketchPad based on a selector. Then I load in the image from an input.
- $('#file-input').change(function (e) {
- var file = e.target.files[0],
- imageType = /image.*/;
-
- if (file === undefined)
- return;
-
- if (!file.type.match(imageType))
- return;
-
- img = new Image();
-
- img.onload = function () {
- nimg_width = this.width;
- nimg_height = this.height;
-
- var reader = new FileReader();
- reader.onload = fileOnload;
- reader.readAsDataURL(file);
- };
-
- img.src = _URL.createObjectURL(file);
-
- });
- if ($("#imageSIZE").val() == "original") {
- img_width = nimg_width;
- img_height = nimg_height;
- myCanvas.width = img_width;
- myCanvas.height = img_height;
- $("#SketchPad").css({
- 'background-image': bgi,
- 'background-size': img_width+"px "+img_height+"px"
- });
- }
Now I want to download my drawing on top of the background image, the background image is loaded in from an input file and resized so I am not sure how to retrieve it. I tried to use the method from
here.
- Sketch.prototype.download = function (format) {
- var mime;
- format || (format = "png");
- if (format === "jpg") {
- format = "jpeg";
- }
- mime = "image/" + format;
-
- var myCanvas = document.createElement('canvas');
- var ctx = myCanvas.getContext('2d');
-
- myCanvas.width = $('#SketchPad')[0].width;
- myCanvas.height = $('#SketchPad')[0].height;
-
- var bg = $('#SketchPad').css('background-image');
- var bf = $('#SketchPad').css('background-size');
-
- bf = bf.replace('px', '').replace('px', '');
- var ret = bf.split(" ");
-
- bg = bg.replace('url(', '').replace(')', '').replace('"', '').replace('"', '');
-
- var im = new Image();
-
- im.onload=function()
- {
- ctx.drawImage(im, 0, 0, ret[0], ret[1]);
-
- ctx.drawImage($('#SketchPad')[0], 0, 0);
-
- return window.open(myCanvas.toDataURL(mime));
- }
-
- im.src = bg;
-
-
- };
Please let me know how I can get the resized background-image and draw it on the canvas. Thanks.
P.S. Nevermind I got it, code modified, thanks for help!