Draw Image Function - image

My friend and I are trying to add images to a canvas using JavaScript; however we have no clue how to even do that and we've tried every possible string of code involving drawing images (such as ones from google, etc), all with failure and we don't even know which direction is the right one to take at this point. Can anyone help? Thanks!

Here's a basic example of what you're seeking.
document.getElementById('inp').onchange = function(e) {
var img = new Image();
img.onload = draw;
img.onerror = failed;
img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0,0);
}
function failed() {
console.error("The provided file couldn't be loaded as an Image media");
}
<input type="file" id="inp">
<canvas id="canvas"></canvas>

Related

Blank texture is rendered when HTML Canvas is used in conjucture with drawImage

I am trying to load a Image from an url and draw it onto a canvas which is used as input for a Texture. I have implemented this on https://jsfiddle.net/9Louwn87/25/ . I have used this following snippet to load the image and create the texture
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
Please can anyone point me to the mistake.
The issue is probably that since you're loading the image yourself and you're loading it from another domain you need to request permission to use the image.
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.crossOrigin = 'anonymous'; // ----------- Add this line
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
note that adding that line does not automatically let you use an image from another website. Rather it asks that website for permission to use the image. Some sites (imgur, flickr, github, threejsfundamentals.org), give that permission. Most sites do not give permission. If the image is on the same domain then you generally do not want to set crossOrigin otherwise unless your server is configured to give permission you won't be able to use local images where as normally if you don't ask then local images just work.
Also, if you had opened the JavaScript console you'd have seen this error
three.min.js:572 Uncaught DOMException: Failed to execute 'texImage2D'
on 'WebGLRenderingContext': Tainted canvases may not be loaded.
One more thing, you can use three.js's ImageLoader which handles this permission issue automatically setting crossDomain if the image is on another domain and not setting it if it's local.
const loader = new THREE.ImageLoader();
loader.load("https://threejsfundamentals.org/threejs/resources/images/wall.jpg", function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
});

HTML canvas how to set image on the back so i can draw on top of it

I am able to get the image behind the drawing canvas but when i start drawing on the canvas the image dissapear
var $ = function(id){return document.getElementById(id)};
var canvas = this.__canvas = new fabric.Canvas('c', {
isDrawingMode: true
});
ctx = canvas.getContext("2d");
var background = new Image();
background.src = "images/pic01.jpg";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
That is not how you draw images using fabric.
Here is the correct way using fabric.Image.fromURL
var canvas = new fabric.Canvas('c', { isDrawingMode: true });
fabric.Image.fromURL('http://i.stack.imgur.com/UFBxY.png', function(myImg) {
canvas.add(myImg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.min.js"></script>
<canvas id="c" width="300" height="300"></canvas>

FireFox : image base64 data using canvas object not working

This is the code i wrote to resize the image in aspect ratio, it works on chrome but not display on firefox, does anyone know what is wrong.
var image = new Image();
image.src = data;
//$(image).load(function () {
var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
parseFloat($(image).prop('naturalHeight')),
dstWidth,
dstHeight);
var canvas = document.createElement('canvas');
canvas.width = dstWidth;
canvas.height = dstHeight;
var x = (dstWidth - aspectRatio[0]) / 2;
var y = (dstHeight - aspectRatio[1]) / 2;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);
return canvas.toDataURL("image/png");
This is work it generated by the canvas.toDataURL
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQEAAADACAYAAAAEL9ZYAAAA1klEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwYD7QAB/UrDfgAAAABJRU5ErkJggg==
To make it work you will need to handle the asynchronous nature of image loading. You will have to use a callback mechanism here. The reason it "works" in Chrome is accident; that is the image happen to be in the cache when you try and/or the browser is able to deliver the uncompressed/decoded image before you use the image in the drawImage call.
This will probably not work when it's online for most users so to properly handle loading you can do -
Example:
function getImageUri(url, callback) {
var image = new Image();
image.onload = function () { // handle onload
var image = this; // make sure we using valid image
var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
parseFloat($(image).prop('naturalHeight')),
dstWidth,
dstHeight);
var canvas = document.createElement('canvas');
canvas.width = dstWidth;
canvas.height = dstHeight;
var x = (dstWidth - aspectRatio[0]) / 2;
var y = (dstHeight - aspectRatio[1]) / 2;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);
// use callback to provide the finished data-uri
callback(canvas.toDataURL());
}
image.src = url; // set src last
}
Then use it this way:
getImageUri(myURL, function (uri) {
console.log(uri); // contains the image as data-uri
});

WebGL single frame "screenshot" of webGL

tried searching for something like this, but I've had no luck. I'm trying to open a new tab with a screenshot of the current state of my webgl image. Basically, it's a 3d model, with the ability to change which objects are displayed, the color of those objects, and the background color. Currently, I am using the following:
var screenShot = window.open(renderer.domElement.toDataURL("image/png"), 'DNA_Screen');
This line succeeds in opening a new tab with a current image of my model, but does not display the current background color. It also does not properly display the tab name. Instead, the tab name is always "PNG 1024x768".
Is there a way to change my window.open such that the background color is shown? The proper tab name would be great as well, but the background color is my biggest concern.
If you open the window with no URL you can access it's entire DOM directly from the JavaScript that opened the window.
var w = window.open('', '');
You can then set or add anything you want
w.document.title = "DNA_screen";
w.document.body.style.backgroundColor = "red";
And add the screenshot
var img = new Image();
img.src = someCanvas.toDataURL();
w.document.body.appendChild(img);
Well it is much longer than your one liner but you can change the background color of the rectangle of the context.
printCanvas (renderer.domElement.toDataURL ("image/png"), width, height,
function (url) { window.open (url, '_blank'); });
// from THREEx.screenshot.js
function printCanvas (srcUrl, dstW, dstH, callback)
{
// to compute the width/height while keeping aspect
var cpuScaleAspect = function (maxW, maxH, curW, curH)
{
var ratio = curH / curW;
if (curW >= maxW && ratio <= 1)
{
curW = maxW;
curH = maxW * ratio;
}
else if (curH >= maxH)
{
curH = maxH;
curW = maxH / ratio;
}
return { width: curW, height: curH };
}
// callback once the image is loaded
var onLoad = function ()
{
// init the canvas
var canvas = document.createElement ('canvas');
canvas.width = dstW;
canvas.height = dstH;
var context = canvas.getContext ('2d');
context.fillStyle = "black";
context.fillRect (0, 0, canvas.width, canvas.height);
// scale the image while preserving the aspect
var scaled = cpuScaleAspect (canvas.width, canvas.height, image.width, image.height);
// actually draw the image on canvas
var offsetX = (canvas.width - scaled.width ) / 2;
var offsetY = (canvas.height - scaled.height) / 2;
context.drawImage (image, offsetX, offsetY, scaled.width, scaled.height);
// notify the url to the caller
callback && callback (canvas.toDataURL ("image/png")); // dump the canvas to an URL
}
// Create new Image object
var image = new Image();
image.onload = onLoad;
image.src = srcUrl;
}

Positioning an HTML5 Canvas Element

I am completely new to HTML5 and have been reading about it for the past few days mainly because I wanted to create a rotating image to put in a <div>. I found a code that does exactly what I want, but it throws the canvas on to the bottom left corner of my page (I'm not sure why, but I think it has something to do with the very first line of the code below). I'm not sure how to adapt the code to a element so that I can put it where I want. From looking at other people's scripts and trying to emulate them, I know you're supposed to do this sort of thing to hold the canvas "<canvas width="100" height="100" id="pageCanvas"></canvas>," but I don't know how to name the below code in order to do that. I greatly appreciate any help anyone can offer me - thank you so much for reading! :)
<script>
window.addEventListener("load", init);
var counter = 0,
logoImage = new Image(),
TO_RADIANS = Math.PI/180;
logoImage.src = 'IMG URL';
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext('2d');
document.body.appendChild(canvas);
function init(){
setInterval(loop, 1000/30);
}
function loop() {
context.clearRect(0,0,canvas.width, canvas.height);
drawRotatedImage(logoImage,100,100,counter);
drawRotatedImage(logoImage,300,100,counter+90);
drawRotatedImage(logoImage,500,100,counter+180);
counter+=2;
}
function drawRotatedImage(image, x, y, angle) {
// save the current co-ordinate system
// before we screw with it
context.save();
// move to the middle of where we want to draw our image
context.translate(x, y);
// rotate around that point, converting our
// angle from degrees to radians
context.rotate(angle * TO_RADIANS);
// draw it up and to the left by half the width
// and height of the image
context.drawImage(image, -(image.width/2), -(image.height/2));
// and restore the co-ords to how they were when we began
context.restore();
}
</script>
Create a canvas element in your HTML code so you can place it exactly where you want (with html + css) :
<canvas id='canvas' height='100' width='100'> Your browser does not support HTML5 canvas </canvas>
And replace this javascript code :
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext('2d');
document.body.appendChild(canvas);
by this one :
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

Resources