Reputation: 127
In HTML5 Canvas I am trying to add and image. The line:
imageObj.src = 'file://C:/Users/User/Documents/Image File/image1.jpg';
is not correct. How do I add a file to HTML5 Canvas Image?
<canvas id="myCanvas" width="1000" height="1000"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var imageObj = new Image();
imageObj.src = 'file://C:/Users/User/Documents/Image File/image1.jpg';
imageObj.onload = function () {
context.drawImage(imageObj, centerX, centerY);
};
</script>
Upvotes: 3
Views: 7367
Reputation: 3358
The below example will explain how to use relative paths.
Assume the project structure is like this:
project(think of this as root)/
|->index.html
|->css/
|->main.css
|->images/
|-> cartoon.jpg
|->cat.jpg
|->other_pages/
|->about.html
|->contact.html
Now if we are in index.html page and we should set the image src as:
img = new Image();
cat = new Image();
//accessing cat.jpg
cat.src = "cat.jpg";
//accessing cartoon.jpg
img.src = "images/cartoon.jpg";
Now lets move to about.html page, here we can access the images in the following manner:
img = new Image();
cat = new Image();
//accessing cat.jpg
cat.src = "../cat.jpg";
// accessing cartoon.jpg
img.src = "../images/cartoon.jpg";
// here .. signifies moving one step back
//.. is similar to executing **cd ..** in command line.
For absolute path try this:
Right click on the image and open it in browser, copy the path and set it in imageObj.src (you can use this method if you are working in local environment and want to test it out with few of your local images.)
Upvotes: 2
Reputation: 56
imageObj.src should be a relative path. For example to an image in the same path, if would be something like imageObj.src = 'image1.jpg'; Path is relative to the html file that is running.
Upvotes: 1