Posts

Showing posts with the label html5-canvas

Canvas drawImage scaling

Canvas drawImage scaling I'm trying to scale an image proportionately to the canvas. I'm able to scale it with fixed width and height as so: context.drawImage(imageObj, 0, 0, 100, 100) But I only want to resize the width and have the height resize proportionately. Something like the following: context.drawImage(imageObj, 0, 0, 100, auto) I've looked everywhere I can think of and haven't seen if this is possible. 3 Answers 3 context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width) solution of @TechMaze is quite good. here is the code after some correctness and introduction of image.onload event. image.onload is too much essential in order to abstain from any kind of distortion. function draw_canvas_image() { var canvas = document.getElementById("image-holder-canvas"); var context = canvas.getContext("2d"); var imageObj = document.getElementB...

Images not displaying the first time in this object program in JS

Images not displaying the first time in this object program in JS I am making a battleship game with polar coordinates. After the user chooses two points, a battleship should be drawn in the middle. My Battleship constructor looks like this: function Battleship(size, location, source){ this.size = size; //initializing the image this.image = new Image(); this.image.src = source; this.getMiddlePoint = function(){ //get midpoint of ship ... } this.distanceBetween = function(t1, t2){ //dist between two points } this.display = function(){ var point = [this.radius]; point.push(this.getMiddlePoint()); point = polarToReal(point[0], point[1] * Math.PI / 12); //now point has canvas coordinates of midpoint var width = this.distanceBetween(this.info[0][0], this.info[this.info.length-1][0]); var ratio = this.image.width / width; ...

toDataURL's output is base64, how to reduce the uploading time and bandwidth of a factor 1/3?

toDataURL's output is base64, how to reduce the uploading time and bandwidth of a factor 1/3? The goal of the following code is to compress the input file (2 MB JPG file => 500 KB file) and then upload it to server when submitting the <form> . <form> When importing an image from a JPG file into a canvas, and exporting it with toDataURL with: toDataURL function doit() { var file = document.getElementById('file').files[0], canvas = document.getElementById('canvas'), hidden = document.getElementById('hidden'), ctx = canvas.getContext("2d"), img = document.createElement("img"), reader = new FileReader(); reader.onload = function(e) { img.src = e.target.result; } img.onload = function () { ctx.drawImage(img, 0, 0); hidden.value = canvas.toDataURL("image/jpeg", 0.5); } reader.readAsDataURL(file); } <input type="file...