我该如何添加选项,让用户能够使用JavaScript将自己的图像添加到益智游戏中

How would I add the option to give the user the ability to add their own image to a picture puzzle game using JavaScript?

本文关键字:添加 JavaScript 能够使 自己的 益智游戏 图像 用户 何添加 选项      更新时间:2023-09-26

我想让用户能够在我的游戏(一款益智游戏(中使用自己的图像,而不是使用我自己上传的默认图像。

因此,例如,游戏应该提示用户选择"使用默认图像"或"浏览您自己的图像"来使用。我完全不知道从哪里开始,任何帮助都将不胜感激。

干杯。

您可以使用默认图像,并让用户使用文件input选择一个文件。如果用户选择了一个文件,请读取该文件并使用FileReader将其转换为URL。并使用此URL。试试看:

var defaultImg = 'http://i.imgur.com/hMyn5YW.jpg',
    imgToUse = defaultImg;
document.getElementById('defaultBtn').addEventListener('click', startPuzzle);
document.getElementById('customImg').addEventListener('change', getCustomImg);
function getCustomImg(){
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            imgToUse = e.target.result;
            startPuzzle();
        }
        reader.readAsDataURL(this.files[0]);
    } else {
        alert('No file was added');
    }
}
function startPuzzle(){
    document.body.innerHTML = '<img src="'+imgToUse+'"/>';
}
<button id="defaultBtn">Use default image</button>
<p>or choose an image from your computer:</p>
<input type='file' id="customImg" />

jQuery版本:

var defaultImg = 'http://i.imgur.com/hMyn5YW.jpg',
    imgToUse   = defaultImg;
$('#defaultBtn').on('click', startPuzzle);
$('#customImg').on('change', getCustomImg);
function getCustomImg(){
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            imgToUse = e.target.result;
            startPuzzle();
        }
        reader.readAsDataURL(this.files[0]);
    } else {
        alert('No file was added');
    }
}
function startPuzzle(){
    $('body').html('<img src="'+imgToUse+'"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button id="defaultBtn">Use default image</button>
<p>or choose an image from your computer:</p>
<input type='file' id="customImg" />