svg -> img conversion not preserving linked font - javascript

I'm trying to convert svgs to png's in javascript by way of canvas elements (inspired by "https://bl.ocks.org/biovisualize/8187844"), but I'm having issues rendering fonts which I'm linking to.
See the fiddle: https://jsfiddle.net/2chtz7rx/1/
Html:
<link href="https://fonts.googleapis.com/css?family=Creepster:400,400" rel='stylesheet' type='text/css'>
<svg id="svg">
<text style="min-height: 43px; margin: 20px; font-size: 200%; font-family: Creepster; font-weight: 400; font-style: normal" x="50%" y="35" text-anchor="middle">FONT</text>
</svg>
<button id="button">render canvas</button>
<img id="img">
<canvas id="canvas"></canvas>
Javascript:
document.getElementById('button').onclick = function() {
var str = new XMLSerializer().serializeToString(document.getElementById('svg'))
var svg = new Blob([str], {type: "image/svg+xml;charset=utf-8"});
var url = self.URL.createObjectURL(svg);
var img = document.getElementById('img');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
self.URL.revokeObjectURL(url);
};
img.src = url;
}
Notice how the svg renders fine, but when creating the img using the svg's url it fails to render the font correctly, and reverts to Times new Roman.
Any advice? Thanks!

Related

Cannot render an image when source passed in as a variable

I am writing a code that takes in an image and pastes it into an HTML canvas. The code works when I declare my <img> in the HTML file, but this does not allow the user to input a new file.
Here is the html structure (the program works if the tag line is put back in:
<style type='text/css'>
canvas{
border: 10px solid black;
}
</style>
</head>
<body>
<canvas id='balls'>
</canvas>
<canvas id='hide' style:'border: 10px solid black;'>
<!-- <img id="taco" width="300" height="300" src="prime.png"> -->
</canvas>
<div>
<input id='url' placeholder="image url">
<button id='submit'>Submit</button>
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<script src="client.js" async defer></script>
</body>
</html>
Here is the portion of JS code I am working on:
$(document).ready(onReady);
var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height= 300;
let bounced = false;
let newPic = `id="taco" width="300" height="300" src="prime.png"`
function onReady(){
$('#submit').on('click', updateImage)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
function updateImage() {
newPic= `id="taco" width="300" height="300" src="${$('#url').val()}" alt="prime.png"`
//console.log(newPic)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
let c, can, ctx, img
function makeCanvas(){
c = canvas.getContext('2d');
can=document.getElementById("hide");
console.log(can)
can.width = 300;
can.height = 300;
ctx=can.getContext("2d");
img=document.getElementById("taco");
ctx.drawImage(img,10,10);
console.log(img)
console.log(ctx.drawImage(img,10,10))
}
My console.log statements for img are identical when the code in the HTML file is placed back in.
When you're setting up your canvas, your image isn't loaded at all. So your
ctx.drawImage(img,10,10);
call just draws... an unloaded image... an empty set of bytes... Nothing.
So you should first load your image. After that, drawing stuff will easily be done. Here's a little code example:
var canv, ctx, img;
function setup() {
//Setting up canvas
//Fetching Context
ctx = canv.getContext("2d");
//Now drawing our image
ctx.drawImage(img,10,10);
}
img = new Image();
img.onload = setup; //We'll setup the canvas after the image is fully loaded
img.src = "your/path/or/variable/pointing/to/your/image.ext";
Hope it helps!

Failing to place an image in canvas

I am trying to place an image inside the canvas element. My code is below. When I execute it I am not getting any errors back, just a page with the outline of the border area of my canvas. Please can someone advise on where I am going wrong?
html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> </title>
<link rel='stylesheet' href="crop_pic.css">
</head>
<body>
<div>
<canvas id="panel" width="380" height="380"></canvas>
</div>
</body>
<script src=crop_pic.js></script>
</html>
javascript:
window.onload = function(){
var canvas = document.getElementById('panel');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'storage/resized_Glong.jpg';
ctx.drawImage(img,0,0);
}
css:
#panel{
border: 1px solid #000;
}
Use quotes in your script tag
<script src='crop_pic.js'></script>
Wait until the image is loaded and then draw it to canvas. For this add an event listener.
window.onload = function() {
var canvas = document.getElementById('panel');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'storage/resized_Glong.jpg';
img.addEventListener('load', function() {
ctx.drawImage(img, 0, 0);
});
}

Troubles applying CSS to a SVG

this is my first time here. I load a SVG with Javascript into an HTML document. I need to replace the color of this SVG (it's a black image with transparency), which is placed into a canvas; however, when I put the css (style), nothing happens.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>TEST CANVAS</title>
<script>
function draw_img(){
var img = document.getElementById("test");
test.width = 300;
test.height = 300;
var ctx = test.getContext('2d');
var source = new Image();
source.src = './field/image.svg';
source.onload = function(){
ctx.drawImage(source, 0, 0);
}
}
</script>
</head>
<style>
canvas#test {
fill:darkred;
}
</style>
<body onload = "draw_img();">
<h1>TEST</h1>
<canvas id="test"></canvas>
</body>
</html>
What's wrong with it? Sorry for my bad English and thanks in advance
Canvasses are bitmap images. You can't apply CSS styles to them and expect that to change their colour. Once the SVG is rendered into the Canvas, it's contents are fixed, and can't be changed (except by pixel manipulation).
If you want to manipulate the colours of your SVG, you should inline it.
<style>
svg#test {
fill:darkred;
}
</style>
<body>
<h1>TEST</h1>
<svg id="test">
<rect width="50" height="50"/>
</svg>
</body>
Demo here

Why doesn't context.drawImage() work in html canvas?

I'm trying to put the image file "sticky.png" into a canvas box, but all I'm getting is a blank canvas. Can anyone point out what I'm doing wrong and/or give me code that works?
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
<body>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};
</script>
</body>
You need to include the sticky.src before sticky.onload.
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
};
</script>
</body>
Fiddle
sometimes as a workAround we have to load the image before the canvas. It's very unusual, but it WORKS. And then you just hide the image. Don't forget to use setTimeOut to wait till image is loaded!
setTimeout("paintStar()", 2000);
function paintStar() {
var canva3 = document.getElementById('canvas3');
canva3.width = 640;
canva3.height = 480;
var ct3 = canva3.getContext('2d');
var img = new Image();
img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo';
ct3.drawImage(img, 0, 0);
ct3.drawImage(img, 0, 0, 20, 20, 10, 200, 20, 20);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CANVAS</title>
<style>
.canvas-1 {
width: 640px;
height: 480px;
border: 1px solid #777;
}
.img-1 {
display: none;
}
</style>
<script src="canva3.js" defer></script>
</head>
<body>
<div class="img-1"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo" alt=""></div>
<canvas id="canvas3" style="border: 2px solid #444;">Doesn't work!</canvas>
</body>
</html>

Javascript, displaying a transparent image.

<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 320px;
height: 480px;
border: 1px solid red;
}
</style>
</head>
<body>
<div style="position: relative;" id="container">
<canvas id="myCanvas" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="plane" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="canvas2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<img id="scream" src="http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png" alt="The Scream" width="0" height="0">
<script>
var c=document.getElementById("myCanvas");
var c2=document.getElementById("canvas2");
var c3=document.getElementById("plane");
var plane;
var ground;
var score1 = "1"
var score = score1;
var increase = 6;
var delay = 40;
var scorez;
start();
function start(){
backgrounds();
planeDraw();
var scorez = setInterval(scoring, delay);
}
function backgrounds(){
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0, 280);
my_gradient.addColorStop(0,"white");
my_gradient.addColorStop(1,"blue");
ctx.fillStyle=my_gradient;
ctx.fillRect(0,0,320,480);
ground = c.getContext("2d");
ctx.fillStyle="black";
ctx.fillRect(0,450 , 320 ,30);
}
function scoring(){
scores();
score2();
}
function scores(){
score -= 3-(3+increase);
}
function score2(){
//var canvas = document.getElementById('canvas2');
var context = c2.getContext('2d');
context.clearRect(0, 0, c2.width, c2.height);
var w = c2.width;
c2.width = 1;
c2.width = w;
var text=c2.getContext("2d");
text.font="20px Georgia";
text.fillText(score ,15,20);
}
function hit(){
}
function loes(){
clearInterval(scorez);
}
function planeDraw(){
plane = c3.getContext('2d');
var img = new Image();
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
plane.drawImage(img, 0, 0, 320, 100);
}
</script>
<!--
http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png
--!>
</body>
</html>
All the code seems to be working fine, the only issue I am finding is the image of the plane is not printing. Could some one please tell me what I am doing wrong. Thank you.
When I changed the planeDraw function to create a rectangle it worked perfectly. As well as this the code worked in JSFiddle, when it was isolated.
You are drawing the image before it has loaded.
Load the plane image once, and draw it after its onload event has fired.
If you can, consider embedding the image as a data: URL, as this will remove the need for waiting for the image to load, however keep in mind that it makes your code bigger!
You have to wait for the image to load before drawing it.
Try:
img.onload = function()
{
plane.drawImage(img, 0, 0, 320, 100);
};
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
It's best to define the onload function before setting the src attribute - depending on the browser, if the image file is in your cache, the onload event may fire as soon as the src is set (before you have a chance to define onload).

Categories

Resources