Preload canvas before html body? - javascript

I have a basic webapp that uses canvas frames to render content on each webpage. On loading the page, chrome will render a single blank canvas frame before the main content is rendered (~20ms or so of blank frame).
When clicking through multiple pages, the blank frame is visually distracting and results in a bad user experience.
Is there a way to pre-render the canvas frame before chrome lays out the page? Or is there a way to have the canvas frame ready so that chrome does not display a blank frame?
The basic code outline looks like this:
<script>
function draw() {
var canvas = document.getElementById("samplecanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0, img.width, img.height,
0, 0, canvas.width, canvas.height);
}
img.src = "data:image/jpeg;base64,...........";
} else {
alert('canvas not supported by this browser')
}
}
</script>
<body onload="draw();">
<canvas id="samplecanvas" width="800" height="800"></canvas>
</body>
Like I said, the above does work, it just results in a blank frame that is really annoying. The base64 embedded image is large (720p), but I still wouldn't expect this to be slow to render.
Any ideas?

Related

how to redraw modified image using canvas

let me explain you what I do. I need to draw bigg image near to 5000px to 2688px. So I can't draw whole image because in browser it's too long. I decided to add scroll bar to see whole image. The following script allows me to draw a part of canvas
var img = new Image();
img.onload = function(){
canvasW = 5376
canvasH = 2688
ctx.drawImage(img, 0,0, canvasW, canvasH);
};
img.src = "image.png";
Now imagine I want to apply effects like blur or brigthness, contrast etc, My canvas will change, so how can I redraw modified canvas (with effect and not the first one.
I tried to check on stackoverflow but the examples is to redraw image from the first one. I mean the drawing is not from a modifed canvas.
I tried to store base64 of my canvas and redraw by using base64 :
var image = new Image()
image.addEventListener('load', function() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.drawImage(image, canMouseX, canMouseY, canvasW, canvasH);
})
image.src = bases64[bases64.length - 1]
It doesn't work because by storing base64 there is just a part of canvas that is redraw. If you want more details clone my repo on : https://github.com/wyllisMonteiro/draggingScroll/tree/master
I want to find a solution to redraw a modified canvas

How can I make a image appear in javascript (and scroll whilst zoomed in)

I am very new to JavaScript. I'm trying to create a basic infinite runner game, but I'm stuck on one little issue. I need a image to print out on my HTML canvas, but when I try to nothing happens. I am creating this game with basic JavaScript. No AJAX/jQuery. Here's my code, and what I have tried.
//this is my code as of right now for printing images.
function make_base () {
base_image = new Image();
base_image.src = 'picture.png'
}
//draw the image to the canvas 2d context
cc.drawImage(base_image, 0, 0);
What this is doing, is nothing. It is not showing any sign of a image. Here's some other code I've gotten, as from w3schools (they're awesome :) )
//image source by html hidden element
var img = document.getElementById("picture");
cc.drawImage(img, 10, 10);
</script>
<image src="picture.png" id="picture" hidden></image>
This is doing the same thing that the new code is doing. Showing absolutely nothing. I'm not sure why, I've tried with Google Chrome, Firefox, and Internet Explorer. All of them with the file uploaded to my website, and with file:///c:/users/name/desktop/js/one.html. Nothing is showing up on the canvas for some strange reason. I've also told Chrome to always use JavaScript. Not only this, but how can I make it zoom in, and scroll from left to right (I can add the blocks/variables that "kill"/make the player restart)?
You probably need to wait for the image to load before trying to draw it.
const c = document.querySelector('canvas')
const cc = c.getContext('2d');
drawImage();
function drawImage() {
const image = new Image();
image.onload = function() {
cc.drawImage(image, 0, 0)
}
image.src = "//placecage.com/200/300"
}
<canvas width="500" height="500"></canvas>
Also, it's <img> not <image>. I haven't checked this, but some browsers don't allow loading things if you're on file://, you'll have to spin up a small server and serve from localhost.

How to get a high quality canvas to PNG conversion

I have a requirement to take the canvas from a webpage and convert it to PDF in the backend so it can be saved on the server and downloaded & printed at a later time at 600 DPI.
I have followed this question, and I have a working prototype of the code: AJAX call to send the canvas to backend in Base64 and then a Java function to convert it to PDF.
However, the problem is that the quality of the image is dependent on the screen/browser window size the user has when he clicks the button to trigger the image creation - a fullscreen browser will create a higher-res image than a partial window browser. Example: Both taken on my PC but on the latter the window is about half the screen size.
I was thinking of somehow creating the canvas on a headless browser with preset size, and that would at least make the quality consistent across users, but I have no idea how to dynamically change the image so I can keep it at 600 DPI no matter the paper size the user chooses to use.
Do I have to draw the canvas shapes directly onto PDF? I know that would fulfill the DPI requirement, but is that even possible to do from an AngularJS/Java stack?
You can decide the proper size for the canvas and then modify the way it's displayed via CSS. Here, the final size is set as 2000x2000 and it will be saved as such (by clicking on it), regardless of the viewport size:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Draw the ellipse
ctx.beginPath();
ctx.lineWidth = 10;
ctx.ellipse(1000, 1000, 500, 800, Math.PI / 4, 0, 2 * Math.PI);
ctx.stroke();
// Draw the ellipse's line of reflection
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(0, 2000);
ctx.lineTo(2000, 0);
ctx.stroke();
canvas.addEventListener('click', function (e) {
var dataURL = canvas.toDataURL('image/png');
var link = document.createElement("a");
link.download = "finalsize.png";
link.href = dataURL;
link.click();
});
<body style="display:flexbox">
<canvas id="canvas" width="2000" height="2000" style="width:100%; "></canvas>
</body>

Loading image into canvas - image scaled

I'm having a problem with loading image into canvas - the image is somehow scaled.
Background: I've got several canvases on my web page, I want to load images into them. When constructing, I'm not sure about the dimension, because the size depends on the screen size.
So I create div and canvas, use css to have it in the size that I want it to have and print an image onto the canvas. There would couple more things to do with the image (i.e. decide based on the ratio if I need to center it vertically or horizontally), but those are not really important at this point. The problem is that the image is rendered "zoomed".
Example: the javascript piece is here:
$("canvas").each(function() {
var context = $(this)[0].getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0);
});
//img will print 400 (correct, thats the width of the img)
//canvas will print based on the screen size (correct)
//img displayed in the canvas shows 300px out of 400px, it's zoomed (not correct)
$(this).parent().append(
'img width: '+img.width+
', canvas width: '+$(this).width());
});
I put the whole example with HTML and CSS to https://jsfiddle.net/7zdrfe58/11/.
I'm trying on Mac. Safari and Chrome work the same (i.e. with the zoom).
I would very appreciate help with this!! Thanks a lot
drawImage lets you specify the width and height of the image. You can get the canvas width like so:
$("canvas").each(function() {
var canvas = this;
var context = canvas.getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0, canvas.width, canvas.height);
});
});
Check out your working code here:
https://jsfiddle.net/ucxdLsq9/
The documentation of the drawImage signatures can be found here:
https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage
Give proper width and height to drawImage.
context.drawImage(this, 0, 0 ,300 ,160);
Updated Fiddle

Javascript draw dynamic image from URL onto canvas element

I am attempting to draw a dynamic PNG image (one that is generated by a PHP script) onto a Canvas element using its URL. I can't really post exact URLs for pages I'm testing this out on, as you must be logged in to the website.
An example of one of the dynamic image URL I'm using is: http://www.website.com/includes/dynamicimage.php?ID=29718958161
If you were logged into this particular website and pasted that URL into your address bar, it would correctly display the image. However, the following Javascript code is not properly drawing it onto the canvas element:
function checkImage(imageContext) {
var canvas = document.createElementNS(
'http://www.w3.org/1999/xhtml', 'canvas');
canvas.width = imageContext.width;
canvas.height = imageContext.height;
var context = canvas.getContext("2d");
var img = new Image();
img.src = imageContext.src;
context.drawImage(img, 0, 0);
newWindow = window.open(imageContext.src, 'newWin', 'width=300,height=300');
newWindow2 = window.open('', 'newWin2', 'width=300,height=300');
newWindow2.document.body.appendChild(canvas);
var imgd = context.getImageData(0, 0, imageContext.width,
imageContext.height);
var pix = imgd.data;
}
I'm having two pop-up windows display both the dynamic image and what is drawn to the canvas, but the canvas is always blank. I am then attempting to do further RGB testing on the image after setting the "pix" variable, but since the image is never drawn to the canvas element, this step fails.
Your problem is that you are not waiting for the image to load before attempting to draw it to the canvas. See the section titled "Playing It Safe" in this question for more details.
In short:
var img = new Image; // First create the image...
img.onload = function(){ // ...then set the onload handler...
ctx.drawImage(img,0,0);
};
img.src = "someurl"; // *then* set the .src and start it loading.

Categories